// pages/my/my.js
import checkLogin from "../../utils/checkLogin";
import {bind} from "../../service/auth";
import utils from "../../utils/util";
import {LoginOut} from "../../service/auth";

Page({

  /**
   * 页面的初始数据
   */
  data: {
        userinfo:{}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    checkLogin('/pages/my/my')
    this.setData({
      userinfo: wx.getStorageSync('userinfo')
    })
  },

  /**
   * 执行绑定或者取消绑定
   */
  handleBind() {
    const openid = wx.getStorageSync('openid')

    const type = this.data.userinfo.openid ? 'unbind' : 'bind'

    const data = {
      type: type,
      openid
    }
    bind(data).then(res => {
      // 绑定成功之后, 更新缓存的用户信息
      const userInfo = this.data.userinfo
      if (type == 'bind') {
        wx.setStorageSync('userinfo', {...userInfo, openid})
      } else {
        wx.setStorageSync('userinfo', {...userInfo, openid: null})
      }

      this.setData({
        userinfo: wx.getStorageSync('userinfo')
      })

      // 提示消息
      wx.showToast({
        title: type == 'bind' ? '绑定成功' : '解绑成功',
        icon: 'success',
        duration: 1500
      })
    })
  },

  /*
  * 退出
  */
  bingLout(){
    LoginOut().then(res=>{
      // 清除缓存
      wx.removeStorageSync('access_token')
      wx.removeStorageSync('userinfo')
      wx.switchTab({
        url:'/pages/index/index'
      })
    })
  }


})